package container_cmds

import (
	"fmt"
	"net"
	"strconv"

	"atomgit.com/openlinksaas/devc/utils"
	"github.com/spf13/cobra"
)

var checkListenCmd = &cobra.Command{
	Use: "checkListen",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 1 {
			return fmt.Errorf("need param [serverPort]")
		}
		port, err := strconv.Atoi(args[0])
		if err != nil {
			return err
		}
		if port < 1024 || port >= 65535 {
			return fmt.Errorf("wrong serverPort must be 1-65534")
		}
		return nil
	},
	RunE: runCheckListen,
}

func runCheckListen(cmd *cobra.Command, args []string) error {
	serverPort := args[0]

	li, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%s", serverPort))
	if err == nil {
		li.Close()
		port, _ := strconv.Atoi(serverPort)
		utils.PrintResult(port)
		return nil
	}
	li, err = net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		return err
	}
	defer li.Close()

	addr, err := net.ResolveTCPAddr(li.Addr().Network(), li.Addr().String())
	if err != nil {
		return err
	}
	utils.PrintResult(addr.Port)
	return nil
}
